package com.sky.strategy;

/**
 *  * date : 2020-08-17
 *  * ------------------策略模式实例-----------------------
 *  * <p>
 *  * 两个数之间的运算有 + - * 等三个运算, 需要输入不同策略来实现同一个计算器下不同的运算方法; 不能修改原有代码, 可以增加代码, 不能使用if else 和其他判断语句;
 *  * 拓展要求, 后面添加一个/ 的运算;
 * @author : wushikai
 */

interface Arithmetic {

    int doOperation(int num1, int num2);
}

class Add implements Arithmetic {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

class Multiply implements Arithmetic {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 * num2;
    }
}

class Subtract implements Arithmetic {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

class Context {
    private Arithmetic arithmetic;

    public Context(Arithmetic arithmetic) {
        this.arithmetic = arithmetic;
    }

    public int executeArithmetic(int num1, int num2) {
        return arithmetic.doOperation(num1, num2);
    }
}


class Calculator {

    public static void main(String[] args) {

        //当我想计算加法的时候, 传入一个加法的策略进来
        Context context = new Context(new Add());
        int i = context.executeArithmetic(1, 2);
        System.out.println("i = " + i);
        //当我想计算乘法的时候, 传入一个乘法的策略进来
        context = new Context(new Multiply());
        i = context.executeArithmetic(1, 2);
        System.out.println("i = " + i);

        //当我想增加一个除法功能的时候
        context = new Context(new Divide());
        i= context.executeArithmetic(4, 2);
        System.out.println("i = " + i);
    }


}


class Divide implements Arithmetic{

    @Override
    public int doOperation(int num1, int num2) {
        return num1 / num2;
    }
}
